package com.cmcc.aregister.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.lazyimage.LazyImageView;
import com.cmcc.aregister.cs.model.Department;
import com.cmcc.aregister.cs.model.Hospital;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.cs.util.Utils;
import com.cmcc.aregister.ui.adapter.DepAdapter;

public class HospitalDetailActivity extends ParentActivity
{
    private static final String TAG = "HospitalDetailActivity";
    // ------view------
    // private TextView dep_list;
    private ImageView attention_layout;
    private Button cancel_btn;
    private Button how_to_btn;
    private LazyImageView image;

    // ------parameter------
    private Hospital hospital;
    private int position;
    private String attention;
    private String area_type;

    private ListView depList;
    private DepAdapter mDepAdapter;

    // ------------
    // 适配首页静态跳转
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        init(R.layout.p_hospital_detail);
    }

    @Override
    protected void setupData()
    {
        Map<String, Object> httpMap = ((PotoalParcelable) getIntent()
            .getParcelableExtra(Arguments.INTENT_TO_NEXT_PAGE)).map;
        hospital = (Hospital) httpMap.get(Arguments.ACTIVITY_JUMP_HOSPITAL);
        position = (Integer) httpMap.get(Arguments.ACTIVITY_JUMP_POSITION);
        area_type = (String) httpMap.get(Arguments.ACTIVITY_JUMP_AREA_TYPE);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "area_type:" + area_type + "---hospital.unit_id:"
                + hospital.unit_id);
        }
        sendGetHospitalDetailTask(ConfigUtilHelper.getMobile(app), area_type,
            hospital.unit_id);
    }

    OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3)
        {
            // TODO Auto-generated method stub
            Intent intent = null;
            Map<String, Object> httpMap = new HashMap<String, Object>();
            PotoalParcelable potoal = new PotoalParcelable(httpMap);
            intent = new Intent(HospitalDetailActivity.this,
                DepartmentDetailActivity.class);
            httpMap.put(Arguments.ACTIVITY_JUMP_DEPARTMENT,
                hospital.dep_list.get(position));
            httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE,
                hospital.dep_list.get(position).area_type);
            httpMap.put(Arguments.ACTIVITY_JUMP_POSITION, position);
            intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    };

    @Override
    protected void setupView()
    {
        depList = (ListView) findViewById(R.id.listview);
        depList.setOnItemClickListener(mOnItemClickListener);
        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.hospital_detail_title);
        // ((TextView)
        // findViewById(R.id.title)).setText(R.string.hospital_detail);
        ((TextView) findViewById(R.id.name)).setText(hospital.unit_name);
        ((TextView) findViewById(R.id.level)).setText(hospital.unit_level);
        ((TextView) findViewById(R.id.address)).setText(hospital.address);
        image = (LazyImageView) findViewById(R.id.image);
        ((TextView) findViewById(R.id.traffic))
            .setMovementMethod(ScrollingMovementMethod.getInstance());
        attention_layout = (ImageView) findViewById(R.id.attention_layout);
        // dep_list = (TextView) findViewById(R.id.dep_list);
        // dep_list.setMovementMethod(ScrollingMovementMethod.getInstance());
        cancel_btn = (Button) findViewById(R.id.cancel_btn);
        how_to_btn = (Button) findViewById(R.id.how_to_btn);
        how_to_btn.setEnabled(false);
        attention = MyApplication.getInstance().hospitalMap
            .get(hospital.unit_id);
        if (attention == null || "".equals(attention))
        {
            attention = hospital.is_attention;
        }
        if ("1".equals(attention))
        {
            cancel_btn.setText(R.string.cancel_attention);
            attention_layout.setVisibility(View.VISIBLE);
            cancel_btn.setBackgroundResource(R.drawable.left_btn_cancel_bg);
        }
        else
        {
            cancel_btn.setText(R.string.confim_attention);
            attention_layout.setVisibility(View.GONE);
            cancel_btn.setBackgroundResource(R.drawable.left_btn_affirm_bg);
        }

        image.loadImage(hospital.image, 0, 0);
        cancel_btn.setOnClickListener(onClickListener);
        how_to_btn.setOnClickListener(onClickListener);
    }

    ArrayList<String> depListStr = new ArrayList<String>();

    public void setView()
    {
        ((TextView) findViewById(R.id.phonenumber))
            .setText(getString(R.string.phone) + hospital.phone);
        ((TextView) findViewById(R.id.traffic)).setText(hospital.bus_route);
        // StringBuffer sb = new StringBuffer();
        for (Department dep : hospital.dep_list)
        {
            // sb.append(dep.dep_name + "\n");
            depListStr.add(dep.dep_name);
        }
        if (hospital.dep_list == null || hospital.dep_list.size() == 0)
        {
            depListStr.add(getString(R.string.no_data));
            depList.setSelector(android.R.color.transparent);
            depList.setOnItemClickListener(null);
            how_to_btn.setEnabled(false);
        }
        else
        {
            how_to_btn.setEnabled(true);
        }
        mDepAdapter = new DepAdapter(this, depListStr);
        depList.setAdapter(mDepAdapter);
    }

    // 跳转到登陆界面
    private void gotoLogin()
    {
        Intent intent = new Intent(HospitalDetailActivity.this,
            UserLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            if (id == R.id.cancel_btn)
            {
                if (!ConfigUtilHelper.isLogin(app))
                {
                    gotoLogin();
                    return;
                }
                else if ("1".equals(hospital.is_attention))
                {
                    sendCancelAttentionTask(ConfigUtilHelper.getMobile(app),
                        "0", area_type, hospital.unit_id);
                }
                else
                {
                    sendConfirmAttentionTask(ConfigUtilHelper.getMobile(app),
                        "0", area_type, hospital.unit_id);
                }
            }
            else if (id == R.id.how_to_btn)
            {
                if (!ConfigUtilHelper.isLogin(app))
                {
                    gotoLogin();
                    return;
                }
                if ("0".equals(hospital.area_type)
                    && ("null".equals(hospital.left_num) || "0"
                        .equals(hospital.left_num)))
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.no_left_num),
                        getString(R.string.close));
                }
                else
                {
                    Intent intent = new Intent(HospitalDetailActivity.this,
                        AppointmentActivity.class);
                    Map<String, Object> httpMap = new HashMap<String, Object>();
                    PotoalParcelable potoal = new PotoalParcelable(httpMap);
                    intent.putExtra(Arguments.ACTIVITY_JUMP_SCREENING_TYPE, 0);
                    httpMap.put(Arguments.ACTIVITY_JUMP_UNIT_ID,
                        hospital.unit_id);
                    httpMap.put(Arguments.ACTIVITY_JUMP_CHOICE_HOSPITAL,
                        hospital.unit_name);
                    httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE,
                        hospital.area_type);
                    intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            }
        }
    };

    /**
     * 获取医院信息
     */
    private HttpAsyncTask sendGetHospitalDetailTask;

    /**
     * 
     * @param mobile 手机号码 如果为空，则不处理关注相关数据
     * @param area_type 区域类别 0：本地 1：异地
     * @param unit_id 医院编号
     */
    private void sendGetHospitalDetailTask(String mobile, String area_type,
        String unit_id)
    {
        logger.d("----------sendGetHospitalDetailTask----------" + mobile
            + "  area_type:" + area_type + " unit_id" + unit_id);
        Log.i("sendGetHospitalDetailTask", "mobile:" + mobile + "  area_type:"
            + area_type + " unit_id" + unit_id);
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("mobile", mobile);
        parameterMap.put("unit_id", unit_id);
        String getHospitalDetailUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_HOSPITAL_DETAIL, parameterMap);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "医院详情url：" + getHospitalDetailUrl);
        }
        sendGetHospitalDetailTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_HOSPITAL_DETAIL, getHospitalDetailUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendGetHospitalDetailTask
            .setUIHandler(sendGetHospitalDetailTaskHandler);
        mHttpManager.execute(sendGetHospitalDetailTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetHospitalDetailTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendGetHospitalDetailTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        Hospital hospital_1 = (Hospital) httpMap
                            .get(Arguments.XML_HOSPITAL);
                        hospital.dep_list = hospital_1.dep_list;
                        hospital.phone = hospital_1.phone;
                        hospital.bus_route = hospital_1.bus_route;
                        hospital.left_num = hospital_1.left_num;
                        hospital.address = hospital_1.address;
                        setView();
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.read_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 我要关注
     */
    private HttpAsyncTask sendConfirmAttentionTask;

    /**
     * 
     * @param mobile 手机号码
     * @param attentionType 关注类别 N 0：关注医院1:关注科室2:关注医生
     * @param area_type 医院区域 N 0：本地 1是异地
     * @param id 相应id
     */
    private void sendConfirmAttentionTask(String mobile, String attentionType,
        String area_type, String id)
    {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", mobile);
        parameterMap.put("area_type", area_type);
        parameterMap.put("unit_id", id);
        String confirmAttentionUrl = Utils.changeUrl(
            Arguments.SERVER_URL_CONFIRM_ATTENTION, parameterMap);
        sendConfirmAttentionTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_CONFIRM_ATTENTION, confirmAttentionUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendConfirmAttentionTask.setUIHandler(sendConfirmAttentionTaskHandler);
        mHttpManager.execute(sendConfirmAttentionTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendConfirmAttentionTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendConfirmAttentionTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        String status = (String) httpMap
                            .get(Arguments.XML_STATUS);
                        String message = (String) httpMap
                            .get(Arguments.XML_MESSAGE);
                        if ("0".equals(status))
                        {
                            attention_layout.setVisibility(View.VISIBLE);
                            cancel_btn.setText(R.string.cancel_attention);
                            cancel_btn
                                .setBackgroundResource(R.drawable.left_btn_cancel_bg);
                            hospital.is_attention = "1";
                        }
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.attention_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.attention_fail),
                    getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 取消关注
     */
    private HttpAsyncTask sendCancelAttentionTask;

    /**
     * 
     * @param mobile 手机号码
     * @param attentionType 关注类别 N 0：关注医院1:关注科室2:关注医生
     * @param area_type area_type 区域ID Y 0是本地 1是异地 2是全部
     * @param id 相应id
     */
    private void sendCancelAttentionTask(String mobile, String attentionType,
        String area_type, String id)
    {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", mobile);
        parameterMap.put("area_type", area_type);
        parameterMap.put("attentionType", "0");
        parameterMap.put("unit_id", id);
        String cancelAttentionUrl = Utils.changeUrl(
            Arguments.SERVER_URL_CANCEL_ATTENTION, parameterMap);
        sendCancelAttentionTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_CANCEL_ATTENTION, cancelAttentionUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendCancelAttentionTask.setUIHandler(sendCancelAttentionTaskHandler);
        mHttpManager.execute(sendCancelAttentionTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendCancelAttentionTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendCancelAttentionTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        String status = (String) httpMap
                            .get(Arguments.XML_STATUS);
                        String message = (String) httpMap
                            .get(Arguments.XML_MESSAGE);
                        if ("0".equals(status))
                        {
                            attention_layout.setVisibility(View.GONE);
                            cancel_btn.setText(R.string.confim_attention);
                            cancel_btn
                                .setBackgroundResource(R.drawable.left_btn_affirm_bg);
                            hospital.is_attention = "0";
                        }
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.cancel_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.cancel_fail), getString(R.string.close));
                break;
            }
        }
    };

    @Override
    protected void setTaskHandlerNull()
    {
        if (sendGetHospitalDetailTask != null)
        {
            sendGetHospitalDetailTask.setTaskBindingHandler(null);
        }
        if (sendConfirmAttentionTask != null)
        {
            sendConfirmAttentionTask.setTaskBindingHandler(null);
        }
        if (sendCancelAttentionTask != null)
        {
            sendCancelAttentionTask.setTaskBindingHandler(null);
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if (!hospital.is_attention.equals(attention))
        {
            app.changeAttention(0, hospital.unit_id, position,
                hospital.is_attention);
        }
    }
}